<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\ContractTemplate;
use App\Models\Medical;
use App\Models\Member;
use App\Support\Support;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Traits\HasFormResponse;
use Dcat\Admin\Widgets\Alert;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpWord\TemplateProcessor;
use zgldh\QiniuStorage\QiniuStorage;

class DownloadController extends Controller
{

    use HasFormResponse;
    public function index(Content $content)
    {
        $request = \request();

        switch ($request->input('cmd')) {
            case 'agreement': // 协议下载

                $medicalModel = Medical::where('id', $request->input('medical_id'))->first();
                if (empty($medicalModel) || empty($medicalModel->agreement_file)) {
                    // 项目协议
                    $tplModel = ContractTemplate::where('id', 1)->first();

                    $user = Member::find($medicalModel->user_id)->load('doctor');
                    if (!empty($medicalModel->examine_time)) {
                        $datetime = Support::getYearMonthDay($medicalModel->examine_time);
                    }


                    // dd(storage_path('app/public/') . $tplModel->url);
                    // if ($path = downloadFile($tplModel->url)) { //TemplateProcessorD:\phpstudy_pro\WWW\2024\yangtze-river\storage\app\public\contract\template\2024\07\668639d004e0b
                    $path  = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' .  DIRECTORY_SEPARATOR . $tplModel->url;

                    if ($path) {
                        // $template = new TemplateProcessor(app()->basePath() . DIRECTORY_SEPARATOR . $path);
                        $template = new TemplateProcessor($path);

                        // todo 套入协议模板数据
                        $template->setValues([
                            'real_name' => $user->doctor['real_name'],
                            'phone' => $user->doctor['phone'],
                            'year' => isset($datetime['year']) ? $datetime['year'] : '',
                            'month' => isset($datetime['month']) ? $datetime['month'] : '',
                            'day' => isset($datetime['day']) ? $datetime['day'] : '',
                            'unit' => $user->doctor['unit'],
                            'id_card_number' =>  $user->doctor['id_card_number'],
                            'opening_bank' => $user->doctor['opening_bank'],
                            'bank_number' => $user->doctor['bank_number'],
                        ]);

                        $pathinfo = pathinfo($path);

                        $newFile = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . 'new-' . $user->doctor['real_name']  . $medicalModel['examine_time'] . '-' . uniqid() . '-' . $pathinfo['basename'];

                        $template->saveAs($newFile);
                        Log::info('-------生成新的协议文件-------', ['newFile' => $newFile]);
                        $filePath = 'uploads/agreement/' . date('Ymd') . '/' . $user->doctor['real_name'] . '-' . $medicalModel['examine_time'] . '-' . uniqid() . '-' . $pathinfo['basename']; //文件路径

                        $res = QiniuStorage::disk('qiniu')->put($filePath, file_get_contents($newFile));
                        Log::info('-------上传七牛云返回结果-------', ['qiniuyun-result' => json_encode($res)]);
                        $agreement_file = '';
                        if ($res) {
                            $obj = QiniuStorage::disk('qiniu')->downloadUrl($filePath);
                            $agreement_file = $obj->getUrl();
                            Log::info('-------获取七牛云的协议地址-------', ['qiniuyun-result' => json_encode($agreement_file)]);
                        }
                        $medicalModel->agreement_file = httpToHttps($agreement_file);
                        $medicalModel->save();
                        Log::info('----------生成协议调度任务结束了----------');
                        // unlink($path);
                        unlink($newFile);
                    }

                    exit('<script> Dcat.error("请稍后, 协议文件生成中", null, {timeOut: 5000}); history.go(-1);</script>');
                } else {
                    $medicalModel = Medical::where('id', $request->input('medical_id'))->first();
                    $medicalModel->agreement_status = 1;
                    $medicalModel->save();
                    exit('<script>window.open("' . $medicalModel->agreement_file . '", "_blank", "noreferrer"); history.go(-1);</script>');
                    break;
                }


            case 'export-agreement': // 导出协议
                $path = $request->input('filePath');
                if (!file_exists($path)) {
                    return responses()->setContent('文件不存在');
                }
                return response()->download($path)->deleteFileAfterSend(true);
                break;
            default:
                $alert = Alert::make('未识别的下载');
                $alert->danger();
                return $alert;
                break;
        }
    }
}
